package com.why.rpc.core.client.channel;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import com.why.rpc.core.client.handler.NettyClientHandler;
import com.why.rpc.core.common.codec.CommonDecoder;
import com.why.rpc.core.common.codec.CommonEncoder;
import com.why.rpc.core.common.serializable.CommonSerializable;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * @program: why-rpc-framework
 * @description:
 * @author: @why
 * @create: 2021-03-17 10:33
 **/
@Slf4j
public class GetChannel {
    private static Bootstrap bootStart;

    private CommonSerializable serializable;

    private GetChannel() {

    }

    static {
        log.info("客户端正在初始化中。。。");
        EventLoopGroup loopGroup = new NioEventLoopGroup();
        bootStart = new Bootstrap();
        bootStart.group(loopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true);
    }

    public static Channel getChannel(CommonSerializable serializable, InetSocketAddress address) {
        bootStart.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                //设置5s没收到写的消息  发送一个包,发送方法触发的是NettyClientHandler中的: userEventTriggered
                pipeline.addLast(new IdleStateHandler(0,6,0, TimeUnit.SECONDS));
                pipeline.addLast(new CommonDecoder());
                pipeline.addLast(new CommonEncoder(serializable));
                pipeline.addLast(new NettyClientHandler());

            }
        });
        log.info("客户端初始化完成！");
        try {
            ChannelFuture future = bootStart.connect(address).sync();

            return future.channel();
        } catch (InterruptedException e) {
            log.error("客户端连接的时候发生了错误。。。");
            e.printStackTrace();
        }
        return null;

    }
}
